<?php

namespace App\Eloqumd\Book;

use Illuminate\Database\Eloquent\Model;
use App\Eloqumd\Book\BookArticleLatest;

class BookArticleCate extends Model
{
    public $timestamps = false;

    public static function getArticleCates($bookID, $parentID = 0, $type = 0)
    {
        $where[] = ['book_id', '=', $bookID];
        $where[] = ['parent_id', '=', $parentID];
        $where[] = ['isdel', '=', 1];
        $cateDataParent = BookArticleCate::where($where)->get()->toArray();
        $jsonData = [];
        if ($cateDataParent) {
            foreach ($cateDataParent as $key => $val) {
                $valData = $type == 1 ? $val : ['id' => $val['id'], 'name' => $val['name']];
                $sub = self::getArticleCates($bookID, $val['id'], $type);
                $subData = [];
                if ($type == 1) {
                    $arts = BookArticleLatest::where('cate_id', $val['id'])->where('isdel', 0)->get()->toArray();
                    if (count($arts)) {
                        foreach ($arts as $ak => $av) {
                            $subData[] = [
                                'id' => 'art_' . $av['id'],
                                'art_id' => $av['id'],
                                'book_id' => $bookID,
                                'name' => $av['title'],
                                'parent_id' => $val['id'],
                                'sysunique' => $av['sysunique'],
                                'author' => $av['author']
                            ];
                        }
                    }
                }
                foreach ($sub as $k => $v) {
                    $subData[] = $type == 1 ? $v : ['id' => $v['id'], 'name' => $v['name']];
                }
                $valData['children'] = $subData;
                $jsonData[] = $valData;
            }
        } else {
            return [];
        }

        return $jsonData;
    }
}
